import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { ActivatedRoute } from '@angular/router';
import { NzModalService } from 'ng-zorro-antd/modal';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';

import { storageDeliveryMethodArrs } from '../../xstorage-manage-pipes/storage-manage-z.pipe';
import { CommonService } from '../../../../services-common/common.service';
import { PermissionService } from '../../../../service/permission.service';
import { StorageCommonService } from '../../xstorage-manage-services/storage-common.service';
import { StoragePurchaseManageService } from '../../xstorage-manage-services/storage-purchase-manage.service';

@Component({
  selector: 'app-storage-purchase-details',
  templateUrl: './storage-purchase-details.component.html',
  styleUrls: ['./storage-purchase-details.component.scss']
})
export class StoragePurchaseDetailsComponent implements OnInit {

  routeParams: any = {};
  detailsData: any = {};

  detailedTableData: any[] = [];

  supplierOptions: any[] = []; // 供应商Options
  warehouseOptions: any[] = []; // 仓库Options
  logisticsOptions: any[] = []; // 物流Options

  /**
   * 作废 Modal
   * ----------------------------------------------------------------
   */
  isZfVisible = false;
  submitZfLoading = false;
  toVoidItem: any = {};
  toVoidRemark = ''; // 作废备注 

  constructor(
    private msg: NzMessageService,
    private activatedRoute: ActivatedRoute,
    private modal: NzModalService,
    private fb: FormBuilder,
    private commonService: CommonService,
    public permission: PermissionService,
    private storageCommonService: StorageCommonService,
    private services: StoragePurchaseManageService
  ) {
    activatedRoute.queryParams.subscribe((res: any) => {
      this.routeParams = res || {};
    })
  }

  ngOnInit(): void {
    this.loadSupplierList();
    this.loadWarehouseList();
    this.loadLogisticsData();

    this.loadDetailsData();
  }

  // 查询物流
  async loadLogisticsData() {
    const res: any = await this.commonService.getDictList('logistics_company');
    this.logisticsOptions = res || [];
  }

  // 查询供应商
  async loadSupplierList() {
    const res: any = await this.commonService.getSupplierList();
    // 状态为正常de
    this.supplierOptions = res.filter((item: any) => item.state === 1);
  }

  // 查询仓库
  async loadWarehouseList() {
    let params = {
      page: 1,
      pageSize: 9999
    }
    const {code, data, message}: any = await this.storageCommonService.getWarehouseList(params);
    if (code === 0) {
      this.warehouseOptions = data?.records.filter((item: any) => [1].includes(item.state));
    } else {
      this.msg.error(message);
    }
  }

  async loadDetailsData() {
    let params = {
      id: this.routeParams.id
    }

    const msgId = this.msg.loading('数据加载中..', { nzDuration: 0 }).messageId;
    const {code, data, message}: any = await this.services. getPurchaseDetailData(params);
    this.msg.remove(msgId);

    if (code === 0) {
      const {purchase, list} = data || {};
      this.detailsData = purchase || {};
      this.detailedTableData = list || [];
      this.detailsData.fileList = purchase.contractEnclosure ? this.handleList(purchase.contractEnclosure.split(',')) : [];
    } else {
      this.msg.error(message);
    }
  }

  /**
   * 作废
   * ----------------------------------------------------------------
   */
  showTovoidModal(item?: any) {
    this.toVoidItem = item;
    this.toVoidRemark = '';

    // 当前行的冻结数量不为0 && 已入库数量不为0
    if ((!this.commonService.isEmpty(item.frozenNumber) && item.frozenNumber > 0) || (!this.commonService.isEmpty(item.stockNumber) && item.stockNumber > 0)) {
      this.msg.warning('该明细行已有未结束的入库信息，无法作废');
    } else {
      this.isZfVisible = true;
    }
  }

  async submitToVoidData() {
    if (this.commonService.isEmpty(this.toVoidRemark)) {
      this.msg.warning('请输入备注');
      return
    }

    let params = {
      id: this.toVoidItem.id,
      state: 1, // 状态 0正常 1已作废
      note: this.toVoidRemark
    }
    this.submitZfLoading = true;
    const {code, message}: any = await this.services.tovoidPurchaseData(params);
    this.submitZfLoading = false;

    if (code === 0) {
      this.isZfVisible = false;
      this.msg.success('操作成功');
      this.loadDetailsData();
    } else {
      this.msg.error(message);
    }
  }

  /**
   * other
   * ----------------------------------------------------------------
   */

  // 入库数量 \ 单价合计
  calcSumTotal(key: string) {
    let sum = 0;
    const calcArrs = this.detailedTableData.filter(ele => ele.lineState === 0);
    sum = calcArrs.reduce((total: number, item: any) => {
      return (total || 0) + (item[key] || 0);
    }, 0);

    return isNaN(sum) ? 0 : sum;
  }

  // 行小计
  calcProduct(num: number, price: number) {
    let pTotal = 0;
    pTotal = num * (price ? (Number(price)) : 0);

    return isNaN(pTotal) ? 0 : pTotal;
  }

  // 小计合计
  calcProductTotal() {
    let sum = 0;
    const calcArrs = this.detailedTableData.filter(ele => ele.lineState === 0);
    sum = calcArrs.reduce((total: number, item: any) => {
      return (total || 0) + ((item.purchaseNumber || 0) * (item.purchasePrice || 0));
    }, 0);

    return isNaN(sum) ? 0 : sum;
  }

  // Filter Text
  filterText(arrs: Array<any>, keyVal: any, idKey: string) {
    let tempObjs: any = {};
    if (arrs.length) {
      tempObjs = arrs.find(item => item[idKey] == keyVal);
    }

    return tempObjs?.name || '-';
  }

  coprText(str: any) {
    this.commonService.copyStr(str);
  }

  downFile(item: any) {
    this.commonService.downLoadUrlFile(item.url);
  }

  pageBack() {
    history.back();
  }

  handleList(arrs: Array<string>) {
    let newArr: Array<any> = [];
    if (arrs) {
      newArr = arrs.map(m => {
        let nArr = m.split('/');
        return {
          name: nArr[nArr.length - 1],
          url: m
        }
      })
    }

    return newArr;
  }
}
